package com.sz.hiling.commons;

import com.sun.org.apache.regexp.internal.RE;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;


//写一个工具类，专门处理http的get，post请求
public class HttpClientUtils {
    //处理get的请求
    public static String executeGetMethod(String url){
        String result=null;
        //创建一个客户端
        HttpClient client=HttpClients.createDefault();
        //get方法
        HttpGet get=new HttpGet(url);
        try {
            HttpResponse httpResponse=client.execute(get);
            HttpEntity entity = httpResponse.getEntity();
            result=EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            get.releaseConnection();
        }
        return result;
    }
    //处理post方法
    public static String executePostMethod(String url,String json){
        String result="";
        //创建客户端
        HttpClient client=HttpClients.createDefault();
        //post方法
        HttpPost post=new HttpPost(url);
        StringEntity stringEntity= new StringEntity(json,"UTF-8");
        post.setHeader("content-type","application/json;charset=utf-8");
        post.setEntity(stringEntity);
        try {
            HttpResponse httpResponse=client.execute(post);
            HttpEntity entity1=httpResponse.getEntity();
            result=EntityUtils.toString(entity1,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            post.releaseConnection();
        }
        return result;
    }

    public static void main(String[] args) {
       String result= HttpClientUtils.executeGetMethod("http://10.1.12.233:80/user/delete?userid="+19);
        System.out.println(result);
    }
}
